//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  SortBoard.m
//  Pizza
//
//  Created by ghwang on 15/3/28.
//  Copyright (c) 2015年 sendInfo. All rights reserved.
//

#import "SortBoard.h"
#import "TopView.h"
#import "HomeBoard.h"
#import "FriendCell.h"
#import "PullLoader.h"
#import "FootLoader.h"
#import "ShopBoard.h"
#import "ShareWeiBo.h"
#import "Masonry.h"

#pragma mark -


@implementation SortItemCell
SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)dataDidChanged
{
    
    Shop *shop = self.data;
    NSString *url = [NSString stringWithFormat:@"%@/%@",[HttpRequest sharedInstance].imageUrl,shop.pic];
    
    [self.photo GET:url useCache:YES placeHolder:[UIImage imageNamed:@"triger.jpg"]];
    
    $(@"name").DATA(shop.title);
    $(@"sellprice").DATA([NSString stringWithFormat:@"%@ 元",shop.saleMoney]);
    $(@"ordernum").DATA([NSString stringWithFormat:@"%@ 单",shop.saleOrderNumber]);

}

@end





@interface SortBoard()
{
	//
    UIImageView *_line;
    BeeUIButton *_lastBtn;
    NSMutableArray *shopDatas;
    int _row;
    int _col;
    UIScrollView *scr;
  
}
@property (nonatomic,assign)NSInteger currentIndex;
@property (nonatomic,strong)BeeUIScrollView *list;
@end

@implementation SortBoard

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )

DEF_MODEL(ShopM, shop)

- (void)load
{
    
    self.shop = [ShopM modelWithObserver:self];
    self.shop.shopType = @"1";
    
}

- (void)unload
{
    
    self.shop = nil;
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    
    
    UIImageView *bgimg = [[UIImageView alloc] initWithFrame:self.bounds];
    bgimg.image = [UIImage imageNamed:@"home-bg"];
    [self.view addSubview:bgimg];
    [self.view sendSubviewToBack:bgimg];
    TopView *headBg = [[TopView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 165)];
    [self.view addSubview:headBg];
    
    
    NSArray *tits = @[@"单店排行",@"连锁排行",@"销售榜",@"扩展榜"];
    for (int i = 0; i<tits.count; i++) {
        
        BeeUIButton *headBtn =[[BeeUIButton alloc] initWithFrame:CGRectMake(i*self.size.width/4, CGRectGetMaxY(headBg.frame), self.size.width/4, 30)];
        [headBtn setTitle:tits[i]];
        [headBtn addTarget:self action:@selector(headBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        headBtn.tag = i+100;
        [headBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        headBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        
        if (i == 0) {
            
            [headBtn setTitleColor:[UIColor colorWithString:@"#ed8929"] forState:UIControlStateNormal];
            
            _line = [[UIImageView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(headBtn.frame)-3, headBtn.size.width-20, 3)];
            _lastBtn = headBtn;
            _line.backgroundColor = [UIColor colorWithString:@"#ed8929"];
            [self.view addSubview:_line];
        }
        
        [self.view addSubview:headBtn];
        
    }
    
    self.list = [[BeeUIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headBg.frame)+30, self.bounds.size.width, self.bounds.size.height-CGRectGetMaxY(headBg.frame)-30)];
    self.list.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.list ];
    self.list .lineCount = 1;
    self.list.headerClass = [PullLoader class];
    self.list.headerShown = YES;
    self.list.footerClass = [FootLoader class];
    self.list.footerShown = YES;
    self.list .animationDuration = 0.25f;
    __weak SortBoard *ws = self;
    self.list .whenReloading = ^{
    
        ws.list.total = ws.shop.shopsArray.count;
        
        for (BeeUIScrollItem *item in ws.list.items ) {
            
            item.size = CGSizeMake(ws.size.width, 120);
            item.clazz = [SortItemCell class];
            item.data = [ws.shop.shopsArray safeObjectAtIndex:item.index];
        }
    
    };
    self.list.whenHeaderRefresh = ^{
        
        
        
        [ws.shop firstPage];
        
    };
    
    self.list.whenFooterRefresh = ^{
        
        [ws.shop nextPage];
        
    };
    
    self.list.headerLoading = YES;
    [self.shop firstPage];
    


}
- (void)headBtnClick:(BeeUIButton*)btn
{

    [btn setTitleColor:[UIColor colorWithString:@"#ed8929"] forState:UIControlStateNormal];
    if (btn != _lastBtn) {
        [_lastBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    _lastBtn = btn;
    self.currentIndex = btn.tag;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        _line.frame = CGRectMake(10+(btn.tag-100)*btn.size.width, CGRectGetMaxY(btn.frame)-3, btn.size.width-20, 3);
        
    } completion:^(BOOL finished) {
        
    }];
    
    

    if (btn.tag == 100) {
        
        self.shop.shopType = @"1";
    }else if (btn.tag == 101){
    
        self.shop.shopType = @"2";
    }else if (btn.tag == 102){
        
        self.shop.shopType = @"3";
    }else if (btn.tag == 103){
        self.shop.shopType = @"4";
        
    }
    
    self.list.headerLoading = YES;
    [self.shop firstPage];
    

}
ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
    [scr removeFromSuperview];
    self.list.hidden = NO;
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3(TopView, HEADBTNCLICK, signal)
{

    BeeUIButton *btn = (BeeUIButton*)signal.object;
    if (btn.tag == 100) {
        [self.stack popToFirstBoardAnimated:YES];
    }else if (btn.tag == 102)
    {
    
        [self presentFriendView];
        
        
    }else if (btn.tag == 103)
    {
 
        [self presentNewsView];
    }

}
- (void)presentNewsView
{
    
    //公告
    
    NewsCell *newsCell = [[NewsCell alloc] initWithFrame:CGRectMake(10, 120, self.size.width-20, self.size.height-120-70)];
    newsCell.RELAYOUT();
    [self presentModalView:newsCell animated:YES transitionType:BeeUITransitionTypeDefault];
    
}
- (void)presentFriendView
{
    
    FriendCell *fcell = [[FriendCell alloc] initWithFrame:CGRectMake(10, 120, self.size.width-20, self.size.height-120-70)];
    fcell.clipsToBounds = NO;
    fcell.RELAYOUT();
    
    [self presentModalView:fcell animated:YES transitionType:BeeUITransitionTypeDefault];
    
}
#pragma mark - 请求结果
ON_SIGNAL2(ShopM, signal)
{
    
    if ([signal is:ShopM.RELOADING]) {
        
        self.list.footerLoading = YES;
        
        
    }else if ([signal is:ShopM.RELOADED])
    {
        [self dismissTips];
        
        if (self.shop.shopsArray.count == 0) {
            
            [self presentMessageTips:@"未查询到相关店铺"];
        }
        
        [self.list setHeaderLoading:NO];
        [self.list setFooterLoading:NO];
        self.list.footerMore = self.shop.more;
        [self.list asyncReloadData];
    }
}
ON_SIGNAL3(SortItemCell, mask, signal)
{

    ShopBoard *shopb = [ShopBoard board];
    shopb.sp = signal.sourceCell.data;
    [self.stack pushBoard:shopb animated:YES];
    

}

#pragma mark - 分享
ON_SIGNAL3(FriendCell, SHAREBTN, signal)
{
    
    BeeUIButton *btn = (BeeUIButton*)signal.object;
    if (btn.tag == 1010) {
        
        [self presentMessageTips:@"暂未开放！"];
        
        
    }else if (btn.tag == 1011){
        [self presentMessageTips:@"暂未开放！"];
        
        
    }else if (btn.tag == 1012){
        
        [ShareWeiBo shareTencentWeiBoWithContent:[[NSUserDefaults standardUserDefaults] objectForKey:@"inviurl"] image:[UIImage imageNamed:@"goodsPhoto"] delegate:self];
        
    }else if (btn.tag == 1013){
        
        [ShareWeiBo shareSinaWeiBoWithContent:[[NSUserDefaults standardUserDefaults] objectForKey:@"inviurl"] image:[UIImage imageNamed:@"goodsPhoto"] delegate:self];
    }
    
}
#pragma mark - 搜索店铺
ON_SIGNAL3(BeeUITextField, RETURN, signal)
{
    
    BeeUITextField *tf = (BeeUITextField*)signal.sourceView;
    if (tf.tag == 9999) {
    self.MSG(HttpAPI.shop_search).INPUT(@"body",@{@"source":@"IOS",@"keywords":tf.text,@"pageNumber":@"1",@"pageSize":@"1000"});
    }

}
ON_MESSAGE3(HttpAPI, shop_search, msg)
{


    if (msg.sending) {
        
        [self presentLoadingTips:@"数据获取中"];
    }else{
        
        [self dismissTips];
        if (msg.succeed) {
            
            Status *sta = msg.GET_OUTPUT(@"status");
            if ([sta.code intValue] != 10000) {
                
                [self presentMessageTips:sta.message];
                return;
            }
            //
            NSArray *sps = msg.GET_OUTPUT(@"shops");
            shopDatas = [[NSMutableArray alloc] initWithArray:sps];
            if (sps.count == 0) {
                
                [self presentMessageTips:@"没有符合条件店铺"];
                return;
            }
            self.list.hidden = YES;
            [self addShopsView:sps];
        }else{
            
            [self presentFailureTips:@"网络错误"];
        }
        
    }

}
- (void)addShopsView:(NSArray*)arr
{

    [scr removeFromSuperview];
    
    
    
    //shareicons = @[[UIImage imageFromString:@"qq"],[UIImage imageFromString:@"weixin"],[UIImage imageFromString:@"tencent"],[UIImage imageFromString:@"sina"]];
    
    _row = (int)(arr.count/2);
    
    if (arr.count%2) {
        
        _row++;
        
    }
    if (arr.count==1) {
        
        _row =1;
    }
    
    scr = [[UIScrollView alloc] init];
    [self.view addSubview:scr];
    [scr mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view).offset(210);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view).offset(0);
        
    }];
    
    for (int i = 0; i<_row; i++) {
        
        UIView *cellBg = [[UIView alloc] initWithFrame:CGRectMake(0, i*120, self.bounds.size.width, 110)];
        cellBg.backgroundColor = [UIColor clearColor];
        [scr addSubview:cellBg];
        [scr setContentSize:CGSizeMake(self.bounds.size.width, CGRectGetMaxY(cellBg.frame))];
        
        
        UIImageView *storeNameImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"storeNmae"]];
        storeNameImg.frame = CGRectMake(10, 0, 21, 100);
        [cellBg addSubview:storeNameImg];
        
        UIImageView *storeNameImgrig = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"storeNmae"]];
        storeNameImgrig.frame = CGRectMake(self.bounds.size.width-30, 0, 21, 100);
        [cellBg addSubview:storeNameImgrig];
        
        UIImageView *bottomBook = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"book"]];
        bottomBook.frame = CGRectMake((cellBg.size.width-240)/2, cellBg.bounds.size.height-29, 240, 57/2);
        [cellBg addSubview:bottomBook];
        
        _col = (i>arr.count/2-1)?1:2;
        
        if (arr.count==1) {
            
            _col = 1;
        }
        
        for (int j = 0; j<_col; j++) {
            
            
            
            BeeUIButton *btn = [[BeeUIButton alloc] init];
            btn.tagString = [NSString stringWithFormat:@"%d|%d",i,j];
            
            //取model
            Shop *ss = arr[2*i+j];
            
            [btn addTarget:self action:@selector(shopBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.frame = CGRectMake(5+(cellBg.size.width-240)/2+j*130, 10, 100, 80);
            
            BeeUIImageView *imgv = [[BeeUIImageView alloc] initWithFrame:CGRectMake(0, 0, btn.size.width, btn.size.height)];
            [btn addSubview:imgv];
            [btn sendSubviewToBack:imgv];
            
            [imgv GET:[NSString stringWithFormat:@"%@/%@",[HttpRequest sharedInstance].imageUrl,ss.pic] useCache:YES placeHolder:[UIImage imageFromString:@"storePhoto"]];
            
            [cellBg addSubview:btn];
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake((btn.size.width-70)/2, btn.size.height-5, 70, 14)];
            lab.text = ss.title;
            lab.textColor = [UIColor whiteColor];
            lab.backgroundColor = RGB(153, 0, 16);
            lab.layer.cornerRadius = 5;
            lab.layer.masksToBounds = YES;
            lab.textAlignment = NSTextAlignmentCenter;
            lab.font = [UIFont systemFontOfSize:14];
            [btn addSubview:lab];
        }
    }


}
#pragma mark - 进入店铺
- (void)shopBtnClick:(BeeUIButton *)btn
{

    if ([SendIFAPPDefault shareAppDefault].userToken.length == 0) {
       
        [self presentMessageTips:@"请先登录"];
        return;
    }
    
    
    NSString *tag = btn.tagString;
    int row = [[[tag componentsSeparatedByString:@"|"] firstObject] intValue];
    int col = [[[tag componentsSeparatedByString:@"|"] lastObject] intValue];
    int index = 2*row+col;
    
    ShopBoard *shb = [ShopBoard board];
    shb.sp = shopDatas[index];
    [self.stack pushBoard:shb animated:YES];

}
#pragma mark - toCart
ON_SIGNAL3(TopView, GOTOCART, signal){
    
    CartBoard *board = [CartBoard board];
    [self.navigationController pushViewController:board animated:YES];
    
}

@end
